package com.rookie.data.generate.util;

import com.rookie.data.generate.constant.enums.ColumnRangeEnum;
import com.rookie.data.generate.model.project.FieldProperties;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 生成器工具类
 *
 * @author rookie
 */
public class GenerateUtils {

    public static final Random RANDOM = new Random();

    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    public static int random(int start, int end) {
        return start + (RANDOM.nextInt(end - start));
    }

    public static int[] getRange(FieldProperties properties, ColumnRangeEnum columnRangeEnum) {
        int newMin = 0, min = 0;
        int newMax = 10000, max = 10000;
        if (columnRangeEnum != null) {
            newMin = min = columnRangeEnum.getMin();
            newMax = max = columnRangeEnum.getMax();
        }
        if (properties.getMinValue() != null) {
            newMin = Math.max(properties.getMinValue(), min);
        }

        if (properties.getMaxValue() != null) {
            newMax = Math.min(properties.getMaxValue(), max);
        }
        if (newMax < newMin) {
            newMax = max;
            newMin = min;
        }
        int[] range = new int[2];
        range[0] = newMin;
        range[1] = newMax;
        return range;
    }

    public static String humpToLine(String str,boolean ignoreTitleCase) {
        if (StringUtils.isBlank(str)){
            return str;
        }
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        String result = sb.toString();
        if (ignoreTitleCase && result.charAt(0) == '_'){
            return result.substring(1);
        }
        return result;
    }
}
